package org.zachary.prosocialbehaviorservice.application;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.ActivityItemWithCategoryDTO;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity.Activity;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity.ActivityItem;
import org.zachary.prosocialbehaviorservice.domain.aggregate_model.activity.ActivityToItem;
import org.zachary.prosocialbehaviorservice.domain.repository.ActivityItemRepository;
import org.zachary.prosocialbehaviorservice.domain.repository.ActivityRepository;
import org.zachary.prosocialbehaviorservice.domain.repository.ActivityToItemRepository;

import java.util.List;
import java.util.Optional;

@Service
public class ActivityQueryService {

    private final ActivityToItemRepository relationRepo;
    private final ActivityItemRepository itemRepo;
    private final ActivityRepository activityRepo;

    public ActivityQueryService(ActivityToItemRepository relationRepo,
                                ActivityItemRepository itemRepo, ActivityRepository activityRepo) {
        this.relationRepo = relationRepo;
        this.itemRepo = itemRepo;
        this.activityRepo = activityRepo;
    }
    @Transactional
    public List<ActivityItemWithCategoryDTO> findAllWithCategory() {
        List<ActivityItem> items = itemRepo.findAll();

        return items.stream().map(item -> {
            // 获取 activityId
            Optional<Integer> activityIdOpt = relationRepo.findActivityIdByItemId(item.getId());

            String activityTitle = "未知";
            if (activityIdOpt.isPresent()) {
                Integer activityId = activityIdOpt.get();
                Optional<Activity> activityOpt = activityRepo.findById(activityId);
                activityTitle = activityOpt.map(Activity::getTitle).orElse("未知");
            }

            return new ActivityItemWithCategoryDTO(
                    item.getId(),
                    item.getTitle(),
                    item.getContent(),
                    item.getStartDate(),
                    item.getEndDate(),
                    item.getPublishDate(),
                    item.getQrCode(),
                    item.getNumber(),
                    activityTitle
            );
        }).toList();
    }

}
